package com.dal.esexercise.controller;


import com.dal.esexercise.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/api/")
@Slf4j
public class UserController {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

//    用户注册接口
    @PostMapping("/register/")
    public String registerUser(@RequestBody User userInfo) {
        log.info("{}",userInfo);
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery("name", userInfo.getName()));
        SearchHits<User> userHits = searchUserHits(queryBuilder);
        if (userHits !=null && userHits.get().count()>0){
                throw new RuntimeException("用户已经存在。");
        };
        elasticsearchRestTemplate.save(userInfo);

        return "ok";
    }

    private  SearchHits<User>  searchUserHits(BoolQueryBuilder queryBuilder) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(queryBuilder);
        NativeSearchQuery build = builder.build();
        try {
            SearchHits<User> user = elasticsearchRestTemplate.search(build , User.class);

            log.info(" {}",  user);
            return user;

        }catch (Exception e){
            log.info(" {}",  e.getMessage());
        }
        return null;
    }

    @GetMapping("/users/")
    List<User> getUsers(){
        List<User> items = new ArrayList<>();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        SearchHits<User> userHits = searchUserHits(queryBuilder);
        userHits.forEach((hits)->items.add(hits.getContent()));

        return items;
    }
    @DeleteMapping("/users/{id}")
    void deleteUsers(@PathVariable("id" ) String id){
        var res=elasticsearchRestTemplate.delete(id, User.class);
        log.info("{}",res);
    }
    @PutMapping("/users/{id}")
    User putUsers(@PathVariable("id" ) String id,@RequestBody User userInfo){
        log.info("{} {}",id,userInfo);
        userInfo.setId(id);
        var res=elasticsearchRestTemplate.save(userInfo);
        log.info("{}",res);
        return res;
    }
}
